import Vue from 'vue'
import VueRouter from 'vue-router'
/* 无论使用与否，都加载一个组件 */
import HomeView from '../views/HomeView.vue'

Vue.use(VueRouter)

const routes = [
  {
    path: '/',
    name: 'home',
    // redirect: '/about', /* 重定向 */
    // redirect: { name: 'about' },
    component: HomeView
  },
  {
    path: '/about',
    name: 'about',
    /* 只有在访问到该页面时才进行组件加载 */
    component: () => import(/* webpackChunkName: "about" */ '../views/AboutView.vue')
  },
  {
    path: '/teacher',
    name: 'teacher',
    // alias: '/ttt', /* 别名和path都可以使用 */
    meta: {
      name: '刘德华'
    },
    component: () => import('@/views/TeacherView.vue')
  },
  {
    /* restful风格 */
    path: '/student/:id/test/:news',
    name: 'student',
    component: () => import('@/views/StudentView.vue')

  },
  {
    path: '/user',
    name: 'user',
    redirect: '/user/list',
    component: () => import('@/views/userinfo/UserView.vue'),
    children: [
      {
        /* 子路由的path一定不能以斜线(/)开头 */
        path: 'list', /* 此时该路由的地址为：/user/list */
        name: 'userList',
        component: () => import('@/views/userinfo/UserListView.vue')
      },
      {
        path: 'edit',
        name: 'userEdit',
        component: () => import('@/views/userinfo/UserEditView.vue')
      }
    ]
  },
  {
    path: '/login',
    name: 'login',
    component: () => import('@/views/LoginView.vue')
  },
  {
    path: '/*',
    name: '404',
    component: () => import('@/views/ErrorView.vue')
  }
]

const router = new VueRouter({
  mode: 'history',
  base: process.env.BASE_URL,
  routes
})
/* 路由守卫 */
router.beforeEach((to, from, next) => {
  const whiteList = ['/', '/teacher', '/login']
  let go = false
  for (const wl of whiteList) {
    if (to.path === wl) {
      go = true
      break
    }
  }
  if (go) {
    /* 放行 */
    next()
  } else {
    const loginId = sessionStorage.getItem('loginId')
    if (loginId) {
      next()
    } else {
      next('/')/* 使用next函数进行重定向 */
    }
  }
})

export default router
